package com.example.select_lesson;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.balysv.materialmenu.MaterialMenuDrawable;

import java.util.ArrayList;
import java.util.List;


public class ChooseClassActivity extends ActionBarActivity implements AdapterView.OnItemClickListener ,View.OnClickListener, AdapterView.OnItemLongClickListener {

    public static void actionStart(Context context, String studentId, String classType) {
        Intent intent = new Intent(context, ChooseClassActivity.class);
        intent.putExtra("student_id", studentId);
        intent.putExtra("class_type", classType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }

    private MaterialMenuDrawable materialMenu;
    private String studentId;
    private String classType;
    private BounceListView mListView;
    private SQLiteDatabase db;
    private MyDataBaseHelper dbHelper;
    private List<String> classNameList = new ArrayList<String>();
    private ArrayList<String> selectClassList = new ArrayList<String>();
    private int itemsNumber = 0;
    public static String[] selectClass;
    private ClassNameAdapter adapter;
    private TextView next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.my_dark_blue));
        }
        studentId = getIntent().getStringExtra("student_id");
        classType = getIntent().getStringExtra("class_type");

        //数据库
        dbHelper = new MyDataBaseHelper(this, "StudentManager.db", null, 1);
        dbHelper.getWritableDatabase();
        db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from CLASSROOM where classType=?",
                new String[] {classType});
        if (cursor.moveToFirst()) {
            do {
                String className = cursor.getString(cursor.getColumnIndex("className"));
                classNameList.add(className);
                itemsNumber++;
            } while (cursor.moveToNext());
        }
        cursor.close();

        selectClass = new String[itemsNumber];

        init();
        setToolbar();
    }

    private void init() {
        mListView = (BounceListView) findViewById(R.id.list_view);
        adapter = new ClassNameAdapter(ChooseClassActivity.this, R.layout.item_choose_class, classNameList);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        next = (TextView) findViewById(R.id.tv_next);
        next.setVisibility(View.GONE);
        next.setOnClickListener(this);
    }

    private void setToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("  " + classType + "课");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                switch (materialMenu.getIconState()) {
                    case BURGER:
                        break;
                    case ARROW:
                        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
                        finish();
                        break;
                    case X:
                        break;
                    case CHECK:
                        break;
                }

            }
        });
        materialMenu = new MaterialMenuDrawable(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN);
        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
        toolbar.setNavigationIcon(materialMenu);
        materialMenu.setNeverDrawTouch(true);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_choose_class, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (selectClass[position] == null) {
            selectClass[position] = classNameList.get(position);
        } else {
            selectClass[position] = null;
        }
        adapter.notifyDataSetChanged();
        Boolean isNull = true;
        for (int i = 0; i < itemsNumber; ++i) {
            if (selectClass[i] != null) {
                isNull = false;
            }
        }
        if (!isNull) {
            next.setVisibility(View.VISIBLE);
        } else {
            next.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_next:
                for (int i = 0; i < itemsNumber; ++i) {
                    if (selectClass[i] != null) {
                        selectClassList.add(selectClass[i]);
                    }
                }
                SelectLessonTestActivity.actionStart(getApplicationContext(), studentId, selectClassList);
                /**
                 * 这里跳转，之后加入龙哥写的activity的名字
                 */
//                Intent intent = new Intent(this, XXXX.class);
//                intent.putStringArrayListExtra("class_name_list", selectClassList);
//                intent.putExtra("studentId", studentId);
//                startActivity(intent);
 /*               String test = "";
                for (int i = 0; i < selectClassList.size(); ++i) {
                    test += selectClassList.get(i);
                    test += ",";
                }
                Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
                selectClassList.clear();
                for (int i = 0; i < itemsNumber; ++i) {
                    selectClass[i] = null;
                }*/
                adapter.notifyDataSetChanged();
                next.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        String classType = "";
        String classCollege = "";
        int studentNumber = 0;
        Cursor cursor = db.rawQuery("select * from CLASSROOM where className=?",
                new String[] {classNameList.get(position)});
        if (cursor.moveToFirst()) {
            do {
                classType = cursor.getString(cursor.getColumnIndex("classType"));
                classCollege = cursor.getString(cursor.getColumnIndex("classCollege"));
                studentNumber = cursor.getInt(cursor.getColumnIndex("studentNumber"));
            } while (cursor.moveToNext());
        }
        cursor.close();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("课程信息");
        builder.setMessage("课程名称："+ classNameList.get(position)
                +"\n出课系：" + classCollege
                + "\n课程性质：" + classType
                + "\n应招学生人数：" + studentNumber + "人");
        builder.setNegativeButton("好的", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder.show();
        return true;
    }
}

class ClassNameAdapter extends ArrayAdapter<String> {

    private int resouceId;


    public ClassNameAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
        resouceId = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String className = getItem(position);
        View view;
        view = LayoutInflater.from(getContext()).inflate(resouceId, null);
        TextView textView = (TextView) view.findViewById(R.id.tv_item);
        textView.setText(className);
        if (ChooseClassActivity.selectClass[position] != null) {
            view.setBackgroundColor(view.getResources().getColor(R.color.my_light_light_blue));
        }
        return view;
    }
}

